﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EasyMvc.Web.Common;
using EasyMvc.Models;
using EasyMvc.Controls;
using EasyMvc.Core;
using EasyMvc.Utility;

namespace EasyMvc.Web.Areas.MWeb.Controllers
{
    public class CategoryController : MWebControllerBase
    {
        // GET: /Index/
        public ActionResult Index(Category model, int id = 1)
        {
            IQueryable<Category> queryList = this.DbContext.Categories;

            if (!string.IsNullOrEmpty(model.Name))
                queryList = queryList.Where(d => d.Name.Contains(model.Name));

            var categories = queryList.OrderByDescending(d => d.Id).ToPagedList(id, this.PageSize);

            return View(categories);
        }

        //
        // GET: /Home/Edit/5

        public ActionResult Edit(int id)
        {
            var model = this.DbContext.Categories.Find(id);

            RenderViewData(model);
            return View(model);
        }

        //
        // POST: /Home/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            if (!ModelState.IsValid)
                return View();

            var model = this.DbContext.Categories.Find(id);
            this.TryUpdateModel<Category>(model);

            this.DbContext.SaveChanges();

            return this.RefreshParent();
        }

        //
        // GET: /Home/Create

        public ActionResult Create()
        {
            var model = new Category();
            RenderViewData(model);

            return View("Edit", model);
        }

        //
        // POST: /Home/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            if (!ModelState.IsValid)
                return View();

            var model = new Category();
            this.TryUpdateModel<Category>(model);

            model.AddTime = DateTime.Now;
            model.Username = this.UserContext.User.Username;

            this.DbContext.Categories.Add(model);
            this.DbContext.SaveChanges();

            return this.RefreshParent();
        }

        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            var ids = Fetch.GetIds("ids");
            ids.ToList().ForEach(id => this.DbContext.Categories.Remove(this.DbContext.Categories.Find(id)));
            this.DbContext.SaveChanges();

            return RedirectToAction("Index");
        }

        private void RenderViewData(Category model)
        {
            
        }
    }
}
